/**
 * 
 */
package edu.gtcfla.km.admin.appmodules.service.impl;

import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;

import javax.annotation.Resource;

import org.vsg.biz.BusinessOperationException;
import org.vsg.biz.account.Menu;
import org.vsg.biz.account.repositories.MenuRepo;

import edu.gtcfla.km.admin.appmodules.service.MenuResourceService;
import edu.gtcfla.km.admin.appmodules.vo.MenuFormView;

/**
 * @author Bill vison
 *
 */
public class MenuResourceServiceImpl implements MenuResourceService {
	
	@Resource
	private MenuRepo<Menu,String> menuRepo;
	
	

	/* (non-Javadoc)
	 * @see org.vsg.crm.sysaccount.service.SysMenuResourceService#saveAndBindingAssoResource(java.util.Set)
	 */
	@Override
	public void registerNewMenuResource(Set<Menu> sysMenuResSet)
			throws BusinessOperationException {

	}



	@Override
	public void updateAll(Set<MenuFormView> menuFormViewSet)
			throws BusinessOperationException {
		// TODO Auto-generated method stub
		
		Set<String> ids = new LinkedHashSet<String>(); 
		for (MenuFormView menuForm : menuFormViewSet) {
			ids.add( menuForm.getId() );
			if (menuForm.getParentId() != null && !menuForm.getParentId().equals("")) {
				ids.add( menuForm.getParentId() );
			}
		}

		Map<String, Menu> menuMap = menuRepo.findAllByIds( ids );

		Set<Menu> updatingMenus = new LinkedHashSet<Menu>();
		
		// --- update all menu ---
		for (MenuFormView menuForm : menuFormViewSet) {
			Menu updateingMenu = menuMap.get(menuForm.getId());
			
			if (menuForm.getName() != null && !menuForm.getName().equals(updateingMenu.getName())) {
				updateingMenu.setName( menuForm.getName() );
			}
			
			if (menuForm.getSortNum() != updateingMenu.getSortNum()) {
				updateingMenu.setSortNum( menuForm.getSortNum() );
			}
			
			if (updateingMenu.getDisabled() != menuForm.getDisabled()) {
				updateingMenu.setDisabled( menuForm.getDisabled() );
			}
			
			if (menuForm.getParentId() != null) {
				// --- update parent id ---
				Menu parentMenu = menuMap.get( menuForm.getParentId() );
				updateingMenu.setParent( parentMenu );
				
				if ( parentMenu != null) {
					int menuLevel = parentMenu.getMenuLevel() + 1;
					updateingMenu.setMenuLevel( menuLevel );
					
					String treeMap = parentMenu.getTreeMap() != null ? parentMenu.getTreeMap() : "";
					if (treeMap.length() > 0) {
						treeMap = "-";
					}
					treeMap+=updateingMenu.getId();
				}
			}
			
			updatingMenus.add(updateingMenu);
		}
		
		menuRepo.updateAll( updatingMenus );
	
		
	}



	@Override
	public void deleteAll(Set<String> menuIds)
			throws BusinessOperationException {
		// TODO Auto-generated method stub
		
		
		Map<String, Menu>  allMenuMap = menuRepo.findAllByIds( menuIds );
		
		menuRepo.deleteAll( new LinkedHashSet<Menu>(allMenuMap.values()) );
	}


	
	
}
